﻿#include "TextView.h"
#include "qstring_ex/qstringex.h"
#include "dir_mgr/DirMgr.h"
#include <QBrush>
#include <QScrollBar>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QTextCodec>
#include <QSettings>

TextView::TextView(QString ProcNamestr, QWidget * parent) : QListWidget(parent)
{
	m_AllFileNameStr.clear();
	m_ProcNameStr.clear();
	m_ProcNameStr = ProcNamestr;
	m_bReading = false;
	m_bWritting = false;
	m_bClearing = false;
	setWrapping(false);
	m_MaxLineNum = MAX_LINE_NUME_100;
	m_CurLineNum = 0;
	m_TempLst.clear();
	m_TextLst.clear();
//	m_LastTime =0;
//	m_IndexCount=0;
	m_TimerShow = NULL;
	m_TimerShow = new QTimer(this);
	connect(m_TimerShow, SIGNAL(timeout()), this, SLOT(TimerProc_Show()));
	m_TimerShow->start(100);
	m_CountNum=0;
	m_RighMenu = NULL;
	m_bAutoRoll = true;
	setupPopMenuBar();
	connect(this, SIGNAL(ViewPopMenu_Signal(QPoint)), this, SLOT(upDateMenu(QPoint)));

}

TextView::~TextView()
{

}
void TextView::TimerProc_Show()
{
	if (m_TimerShow)
	{
		m_TimerShow->stop();
		if (!m_bWritting && !m_bClearing)
		{
			m_bReading = true;
		}
		if (m_bReading)
		{
			AddrStringToShow();
			m_bReading = false;
		}
		m_TimerShow->start(100);
	}
}

//jwj 2012-12-12
void TextView::AddCommBuffToView(QStringList NewStrLst)
{
	if (NewStrLst.count()>0)
	{
		m_TempLst += NewStrLst;
	}
	AddTempToLst();
}

//	显示链路数据报文
void TextView::AddCommBuffToView(XCHAR buff[], XUSHORT len, XUCHAR DataFlag)
{
	if (len<=0 || !buff )
		return;

	XINT			lentemp=0;
	QDateTime		CurTime = QDateTime::currentDateTime();
	XINT			BufPos=0;
	XINT			m_Numline =0;
	XCHAR			msg[TXT_MAX_CHAR_COUNT*2];

	memset(m_TempBuff, 0, TXT_MAX_CHAR_COUNT+1);

	if (TXT_DATA_FLAG_SEND == DataFlag)
	{
		sprintf(m_TempBuff,
			"Send****--发送::[%d]%.2d年%.2d月%.2d日 %.2d时%.2d分%.2d秒\r\n",
			len/3, 
			CurTime.date().year(),
			CurTime.date().month(),
			CurTime.date().day(),
			CurTime.time().hour(),
			CurTime.time().minute(),
			CurTime.time().second());
	}
	else if (TXT_DATA_FLAG_RECV == DataFlag)
	{
		sprintf(m_TempBuff,
			"Recv****--接收::[%d]%.2d年%.2d月%.2d日 %.2d时%.2d分%.2d秒\r\n",
			len/3, 
			CurTime.date().year(),
			CurTime.date().month(),
			CurTime.date().day(),
			CurTime.time().hour(),
			CurTime.time().minute(),
			CurTime.time().second());
	}else
	{
		sprintf(m_TempBuff,
			"Info****--提示::%.2d:%.2d:%.2d ",
			CurTime.time().hour(),
			CurTime.time().minute(),
			CurTime.time().second());
	}

	m_CountNum =(m_CountNum+1)%10000;
	m_TempLst.append(QStringEx::fromLocal8Bit(m_TempBuff));

	for(XINT i=0; i<(len/TXT_MAX_CHAR_COUNT+1); i++)
	{
		BufPos = i*TXT_MAX_CHAR_COUNT;
		lentemp=0;
		if (BufPos > len)
		{
			break;
		}else
		{
			memset(m_TempBuff, 0, TXT_MAX_CHAR_COUNT);	
			if ((len-BufPos) > TXT_MAX_CHAR_COUNT)
			{
				lentemp = TXT_MAX_CHAR_COUNT;
			}else
			{
				lentemp = len-BufPos;
			}
			memcpy(m_TempBuff, buff+BufPos, lentemp);
		}

		if (lentemp>0)
		{
			memset(msg, 0, TXT_MAX_CHAR_COUNT);

			if (TXT_DATA_FLAG_SEND == DataFlag)
			{
				sprintf(msg, "Send%.4d--%.4d::%s\r\n", m_CountNum, ++m_Numline, m_TempBuff);
			}else if (TXT_DATA_FLAG_RECV == DataFlag)
			{
				sprintf(msg, "Recv%.4d--%.4d::%s\r\n", m_CountNum, ++m_Numline, m_TempBuff);
			}else
			{
				sprintf(msg, "Info%.4d--%.4d::%s\r\n", m_CountNum, ++m_Numline, m_TempBuff);
			}
			m_CountNum =(m_CountNum+1)%10000;
			m_TempLst.append(QStringEx::fromLocal8Bit(msg));
		}
	}

	AddTempToLst();
}

//	显示链路数据报文
void TextView::AddCommBuffToView(QString MsgInfoStr, XUCHAR DataFlag)
{
	if (MsgInfoStr.length()<=0)
		return;

	QDateTime		CurTime = QDateTime::currentDateTime();

	memset(m_TempBuff, 0, TXT_MAX_CHAR_COUNT+1);

	if (TXT_DATA_FLAG_ERRO == DataFlag)
	{
		sprintf(m_TempBuff,
			"Erro****--错误::%.2d:%.2d:%.2d ",
			CurTime.time().hour(),
			CurTime.time().minute(),
			CurTime.time().second());
	}else if (TXT_DATA_FLAG_WARN == DataFlag)
	{
		sprintf(m_TempBuff,
			"Warn****--警告::%.2d:%.2d:%.2d ",
			CurTime.time().hour(),
			CurTime.time().minute(),
			CurTime.time().second());

	}else
	{
		sprintf(m_TempBuff,
			"Info****--提示::%.2d:%.2d:%.2d ",
			CurTime.time().hour(),
			CurTime.time().minute(),
			CurTime.time().second());

	}
	m_TempLst.append(QStringEx::fromLocal8Bit(m_TempBuff)+MsgInfoStr/*+QString("\r\n")*/);
	m_CountNum =(m_CountNum+1)%10000;

	AddTempToLst();
}

void TextView::AddTempToLst()
{
	if (!m_bReading && m_TempLst.count()>0 && !m_bClearing)
	{
		m_bWritting = true;
	}
	if (m_bWritting)
	{
		m_TextLst += m_TempLst;
		XINT TxtCount = m_TextLst.count();
		if (m_MaxLineNum>0 &&
			TxtCount>m_MaxLineNum)
		{
			RemoveExcessListStr(TxtCount-m_MaxLineNum);
		}
		m_TempLst.clear();
		m_bWritting = false;
	}
}

void TextView::AddrStringToShow()
{
	XINT  NewLineCount = m_TextLst.count();
	if (NewLineCount > 0)
	{
		QString Str;
		QString FlagStr;
		QListWidgetItem *pItem = NULL;
		for (XINT i=0; i<NewLineCount; i++)
		{
			Str = m_TextLst[i];
			if (Str.length()>4)
			{	
				pItem = NULL;
				pItem = item(i);
				if (!pItem)
				{
					pItem = new QListWidgetItem;
					addItem(pItem);
				}

				if (pItem)
				{
					FlagStr.clear();
					FlagStr = Str.left(4);
					Str.remove(0, 4);
					pItem->setText(Str);

					pItem->setTextAlignment(Qt::AlignLeft|Qt::AlignVCenter);
					
					 if (0 == FlagStr.compare("Erro", Qt::CaseSensitive))
					{
						pItem->setData(Qt::TextColorRole, Qt::red);
					}else if (0 == FlagStr.compare("Warn", Qt::CaseSensitive))
					{
						pItem->setData(Qt::TextColorRole, Qt::darkYellow);
					}else if (0 == FlagStr.compare("expl", Qt::CaseSensitive))
					{
						pItem->setData(Qt::TextColorRole, Qt::darkMagenta);
					}else
					{
						pItem->setData(Qt::TextColorRole, Qt::black);
					}
		//			m_CurLineNum = (m_CurLineNum+1)%m_MaxLineNum;
				}
			}
		}
		m_CurLineNum = count();
		if (m_bAutoRoll)
		{	
			scrollToBottom();
		}
		
	//	m_TextLst.clear();
	}
}

//建立右键菜单
void TextView::setupPopMenuBar()
{
	m_RighMenu=new QMenu("PopMenu",this);
	QAction *action1= m_RighMenu->addAction(QStringEx::fromLocal8Bit("清空"));
	connect(action1, SIGNAL(triggered()), this, SLOT(OnClearText()));
	action1->setData(TXT_POPTYPE_CLEARTEXT);

	QAction *action2= m_RighMenu->addAction(QStringEx::fromLocal8Bit("最大行数100"));
	connect(action2, SIGNAL(triggered()), this, SLOT(OnSetLine100()));
	action2->setData(TXT_POPTYPE_NUM100);
	action2->setCheckable(true);

	QAction *action3= m_RighMenu->addAction(QStringEx::fromLocal8Bit("最大行数200"));
	connect(action3, SIGNAL(triggered()), this, SLOT(OnSetLine200()));
	action3->setData(TXT_POPTYPE_NUM200);
	action3->setCheckable(true);
	
	QAction *action4= m_RighMenu->addAction(QStringEx::fromLocal8Bit("最大行数500"));
	connect(action4, SIGNAL(triggered()), this, SLOT(OnSetLine500()));
	action4->setData(TXT_POPTYPE_NUM500);
	action4->setCheckable(true);

	QAction *action5= m_RighMenu->addAction(QStringEx::fromLocal8Bit("最大行数1000"));
	connect(action5, SIGNAL(triggered()), this, SLOT(OnSetLine1000()));
	action5->setData(TXT_POPTYPE_NUM1000);
	action5->setCheckable(true);

	QAction *action6= m_RighMenu->addAction(QStringEx::fromLocal8Bit("自动滚动屏幕"));
	connect(action6, SIGNAL(triggered()), this, SLOT(OnSetAutoRoll()));
	action6->setData(TXT_POPTYPE_AUTOROLL);
	action6->setCheckable(true);

	QAction *action7= m_RighMenu->addAction(QStringEx::fromLocal8Bit("保存为文本"));
	connect(action7, SIGNAL(triggered()), this, SLOT(OnSavetoFile()));
	action7->setData(TXT_POPTYPE_SAVETOFILE);

}


void TextView::mousePressEvent( QMouseEvent * event )
{
	if (event)
	{
		if (Qt::RightButton == event->button() &&
			QEvent::MouseButtonPress == event->type())
		{
			QPoint point = event->globalPos();
			emit ViewPopMenu_Signal(point);
		}
	} 
	QListWidget::mousePressEvent(event);
}

void TextView::upDateMenu(QPoint point)
{
	if(m_RighMenu==NULL)
	{
		return;
	}
	
	m_RighMenu->popup(point);
	XINT Menu_Count =0;
	XINT i=0;
	QAction * p_action = NULL;
	int    data_menu=0;
	bool   ok =false;
	bool	menuenable=false;
	Menu_Count=0;

	QList<QAction *> PopAction_list;
	PopAction_list =  m_RighMenu->actions();
	Menu_Count=PopAction_list.size();
	if(Menu_Count<=0)return;
	for(i=0;i<Menu_Count;i++)
	{
		menuenable = true; 
		p_action=PopAction_list.at(i);
		data_menu = p_action->data().toInt(&ok);
		if(ok == false)continue;
		switch(data_menu)
		{
		case TXT_POPTYPE_CLEARTEXT:
			{
				if (m_CurLineNum<=0)
				{
					menuenable = false;
				}
			}
			break;
		case TXT_POPTYPE_AUTOROLL:
			{
				p_action->setChecked(m_bAutoRoll);
				menuenable = true;
			}
			break;
		case TXT_POPTYPE_NUM100:
			{
				if (MAX_LINE_NUME_100 == m_MaxLineNum)
				{
					p_action->setChecked(true);
				}else
				{
					p_action->setChecked(false);
				}
			}
			break;
		case TXT_POPTYPE_NUM200:
			{
				if (MAX_LINE_NUME_200 == m_MaxLineNum)
				{
					p_action->setChecked(true);
				}else
				{
					p_action->setChecked(false);
				}
			}
			break;
		case TXT_POPTYPE_NUM500:
			{
				if (MAX_LINE_NUME_500 == m_MaxLineNum)
				{
					p_action->setChecked(true);
				}else
				{
					p_action->setChecked(false);
				}
			}
			break;
		case TXT_POPTYPE_NUM1000:
			{
				if (MAX_LINE_NUME_1000 == m_MaxLineNum)
				{
					p_action->setChecked(true);
				}else
				{
					p_action->setChecked(false);
				}
			}
			break;
		case TXT_POPTYPE_SAVETOFILE:
			{
				if (m_CurLineNum<=0)
				{
					menuenable = false;
				}
			}
			break;
		default:
			menuenable = false;
			break;
		}
		p_action->setEnabled(menuenable);
	}
}

void TextView::OnClearText()
{
	if (m_bReading || m_bWritting)
	{
		return ;
	}
	m_bClearing = true;
	if (m_bClearing)
	{
		clear();
// 		XINT ItemCount = count();
// 		QListWidgetItem *pItem = NULL;
// 		for (XINT i=0; i<ItemCount; i++)
// 		{
// 			pItem = item(i);
// 			if (pItem)
// 			{
// 				pItem->setText("");
// 			}
// 		}
		m_TextLst.clear();
		m_CurLineNum=0;
	}
	m_bClearing = false; 
}

void TextView::OnSetLine100()
{
	if (m_bReading || m_bWritting)
	{
		return ;
	}
	m_bClearing = true;
	if (m_bClearing)
	{
		m_MaxLineNum = MAX_LINE_NUME_100;
		if (m_CurLineNum>MAX_LINE_NUME_100)
		{
			RemoveExcessListStr(m_CurLineNum-m_MaxLineNum);
			RemoveExcessItem(m_CurLineNum-m_MaxLineNum);
			//clear();
			//m_CurLineNum=0;
			m_CurLineNum = m_MaxLineNum;
		}
	}
	m_bClearing = false;
}

void TextView::OnSetLine200()
{
	if (m_bReading || m_bWritting)
	{
		return ;
	}
	m_bClearing = true;
	if (m_bClearing)
	{
		m_MaxLineNum = MAX_LINE_NUME_200;
		if (m_CurLineNum>MAX_LINE_NUME_200)
		{
			RemoveExcessListStr(m_CurLineNum-m_MaxLineNum);
			RemoveExcessItem(m_CurLineNum-m_MaxLineNum);
			//clear();
			//m_CurLineNum=0;
			m_CurLineNum = m_MaxLineNum;
		}
	}
	m_bClearing = false;
}

void TextView::OnSetLine500()
{
	if (m_bReading || m_bWritting)
	{
		return ;
	}
	m_bClearing = true;
	if (m_bClearing)
	{
		m_MaxLineNum = MAX_LINE_NUME_500;
		if (m_CurLineNum>MAX_LINE_NUME_500)
		{
			RemoveExcessListStr(m_CurLineNum-m_MaxLineNum);
			RemoveExcessItem(m_CurLineNum-m_MaxLineNum);
			//clear();
			//m_CurLineNum=0;
			m_CurLineNum = m_MaxLineNum;
		}
	}
	m_bClearing = false;
}

void TextView::OnSetLine1000()
{
	if (m_bReading || m_bWritting)
	{
		return ;
	}
	m_bClearing = true;
	if (m_bClearing)
	{
		m_MaxLineNum = MAX_LINE_NUME_1000;
		if (m_CurLineNum>MAX_LINE_NUME_1000)
		{
			RemoveExcessListStr(m_CurLineNum-m_MaxLineNum);
			RemoveExcessItem(m_CurLineNum-m_MaxLineNum);
			//clear();
			//m_CurLineNum=0;
			m_CurLineNum = m_MaxLineNum;
		}
	}
	m_bClearing = false;
}

void TextView::OnSetAutoRoll()
{
	m_bAutoRoll = !m_bAutoRoll;
	if (m_bAutoRoll)
	{
		scrollToBottom();
	}
}

void TextView::OnSavetoFile()
{
	if (m_bReading || m_bWritting)
	{
		return ;
	}
	m_bClearing = true;
	if (m_bClearing)
	{
		if (count()>0)
		{
			QListWidgetItem *pItem = NULL;
			for (XINT i=0; i<count(); i++)
			{
				pItem = NULL;
				pItem = item(i);
				if (pItem)
				{
					WriteDataToFile(pItem->text());
				}
			}
		}
	}
	m_bClearing = false;

}
void TextView::WriteDataToFile(QString InfoStr)
{
	if (InfoStr.length()<=0)
	{
		return;
	}
	if (m_AllFileNameStr.length()<=0)
	{
		QString dirPathStr;
		dirPathStr = QStringEx::fromLocal8Bit(RCG_DIR_LOGFILE);
		if(!QDir(dirPathStr).exists())
		{
			QDir Dir;
			Dir.mkpath(dirPathStr);
		}
		m_AllFileNameStr = dirPathStr+QStringEx::fromLocal8Bit("//")+m_ProcNameStr+QStringEx::fromLocal8Bit("_Log.txt");
	}
	QFile			writeFile(m_AllFileNameStr);
	QTextStream		writeStream;

	XLONGLONG		EndPos = 0;

	writeStream.setCodec("gbk");

	if (!writeFile.open(QFile::ReadWrite | QIODevice::Text))
	{
		return ;
	}
	writeStream.setDevice(&writeFile);
	EndPos = writeFile.size();
	EndPos = (EndPos+1)%20000;
	writeStream.seek(EndPos);
	writeStream<<InfoStr<<"\n";
	writeStream.flush();
	writeFile.close();
}

void TextView::RemoveExcessListStr(XINT RemoveNum)
{
	if (RemoveNum>0 && m_TextLst.count()>0)
	{
		if (m_TextLst.count()>RemoveNum)
		{
			for (XINT i=0 ;i<RemoveNum; i++)
			{
				m_TextLst.removeFirst();
			}
		}else
		{
			m_TextLst.clear();
		}
	//	qDebug()<<"RemoveExcessListStr"<<RemoveNum;
	}
}

void TextView::RemoveExcessItem(XINT RemoveNum)
{
	XINT ItemCount = count();
	if (RemoveNum>0 && ItemCount>RemoveNum)
	{
		QListWidgetItem *pItem = NULL;
		for (XINT i=0 ;i<RemoveNum; i++)
		{
			pItem = item(0);
			if (pItem)
			{
				delete pItem;
				pItem =NULL;
			}
		}
	//	qDebug()<<"RemoveExcessItem"<<RemoveNum;
	}
}